const DB = require('../db/index');
const enumData = require('../enumeration/index');
const exception = require('../exception');

module.exports = {
    create(data, successFn, failFn) {
        this.findByMobile(data.mobile, (dbRes) => {
            failFn(exception['602'])
        }, (e) => {
            if (e) {
                failFn(exception.ex(e))
            } else {
                try {
                    DB.ReportNoticeRecord.create(data).then((res) => {
                        successFn({code: 0,data:res})
                    });
                } catch (e) {
                    failFn(exception.ex(e))
                }
            }
        });
    },
    update(data, successFn, failFn) {
        this.findById(data.id, (dbRes) => {
            try {
                DB.ReportNoticeRecord.update(data).then(() => {
                    successFn({code: 0})
                });
            } catch (e) {
                failFn(exception.ex(e))
            }
        }, (e) => {
            if (e) {
                failFn(exception.ex(e))
            } else {
                failFn(exception['1302'])
            }
        });
    },
    search(data, successFn, failFn) {
        try {
            DB.ReportNoticeRecord.searchAll(data).then((res) => {
                successFn({
                    code: 0, data: res
                });
            });
        } catch (e) {
            failFn(exception.ex(e))
        }
    },
    delete(data, successFn, failFn) {
        this.findById(data.id, (dbRes) => {
            try {
                DB.ReportNoticeRecord.delete({id: data.id}).then(() => {
                    successFn({code: 0})
                });
            } catch (e) {
                failFn(exception.ex(e))
            }

        }, (e) => {
            e ? failFn(exception.ex(e)) : failFn(exception['1201'])
        });
    },
    findById(merchantId, successFn, failFn) {
        try {
            DB.ReportNoticeRecord.search({id: merchantId}).then((dbResData) => {
                var dbRes = (dbResData || [])[0];
                if (dbRes) {
                    if (successFn) successFn(dbRes);
                } else {
                    if (failFn) failFn();
                }
            })
        } catch (e) {
            if (failFn) failFn(e);
        }
    },
    findByMobile(mobile, successFn, failFn) {
        try {
            DB.ReportNoticeRecord.search({mobile: mobile}).then((dbResData) => {
                var dbRes = (dbResData || [])[0];
                if (dbRes) {
                    if (successFn) successFn(dbRes);
                } else {
                    if (failFn) failFn();
                }
            })
        } catch (e) {
            if (failFn) failFn(e);
        }
    }
};
